package cn.szzsi.api.oauth;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import cn.szzsi.api.util.TokenUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * OauthQQ
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @author L.cm
 * date Jun 24, 2013 9:35:23 PM
 */
public class OauthQQ{
	private static final String AUTH_URL = "https://graph.qq.com/oauth2.0/authorize";
	private static final String TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
	private static final String TOKEN_INFO_URL = "https://graph.qq.com/oauth2.0/me";
	private static final String USER_INFO_URL = "https://graph.qq.com/user/get_user_info";

	private static OauthQQ oauthQQ = new OauthQQ();
	private OauthQQ(){}
	/**
	 * 用于链式操作
	 * @return OauthQQ
	 */
	public static OauthQQ me() {
		return oauthQQ;
	}

	/**
	 * 获取授权url
	 * DOC：http://wiki.connect.qq.com/%E4%BD%BF%E7%94%A8authorization_code%E8%8E%B7%E5%8F%96access_token
	 * @param state OAuth2.0标准协议建议，利用state参数来防止CSRF攻击
	 * @return String 返回类型
	 */ 
	/*public String getAuthorizeUrl(String state) {
		return super.getAuthorizeUrl(AUTH_URL, state);
	}*/

	/**
	 * 获取token
	 * @param code 根据code获取token
	 * @return String 返回类型
	 */
	/*public String getTokenByCode(String code) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("code", code);
		params.put("client_id", getClientId());
		params.put("client_secret", getClientSecret());
		params.put("grant_type", "authorization_code");
		params.put("redirect_uri", getRedirectUri());
		// access_token=FE04************************CCE2&expires_in=7776000
		String token = TokenUtil.getAccessToken(super.doGet(TOKEN_URL, params));
		LOGGER.debug(token);
		return token;
	}*/

	/**
	 * 获取TokenInfo
	 * @param accessToken AccessToken
	 * @return String 返回类型
	 */
	/*public String getTokenInfo(String accessToken) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		// callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
		String openid = TokenUtil.getOpenId(super.doGet(TOKEN_INFO_URL, params));
		LOGGER.debug(openid);
		return openid;
	}*/
	
	/**
	 * 获取用户信息
	 * DOC：http://wiki.connect.qq.com/get_user_info
	 * @param accessToken AccessToken
	 * @param openid 用户id
	 * @return String 返回类型
	 */
	public static JSONObject getUserInfo(String oauth_consumer_key,String accessToken, String openid) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		params.put("oauth_consumer_key", oauth_consumer_key);
		params.put("openid", openid);
		params.put("format", "json");
		// // {"ret":0,"msg":"","nickname":"YOUR_NICK_NAME",...}
		String userinfo = HttpKit.get(USER_INFO_URL,params);
		JSONObject jsonObject=JSON.parseObject(userinfo);
		return jsonObject;
	}


}
